package com.example.peibei.wxapi;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.dingtao.common.util.UIUtils;
import com.example.peibei.OnCallback;
import com.example.peibei.ui.activity.SubmitOrderActivity;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";

    private IWXAPI api;
    public static final String APP_ID = "wx4de7acf350b321e9";
    private static OnCallback<Boolean> onCallback;

    public static void setOnCallback(OnCallback<Boolean> onCallback) {
        WXPayEntryActivity.onCallback = onCallback;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.pay_result);
        api = WXAPIFactory.createWXAPI(this, APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        Log.i("answer", "onPayFinish, errCode = " + resp.errCode);
        if (resp.errCode != -25 && resp.errCode != -2) {
            UIUtils.showToastSafe("支付成功");

        }
        if (onCallback != null){
            onCallback.onCall(resp.errCode == BaseResp.ErrCode.ERR_OK);
            onCallback = null;
        }
        try {
            if (SubmitOrderActivity.submitOrderActivity != null){
                SubmitOrderActivity.submitOrderActivity.newIntent();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finish();
//        SubmitOrderActivity.submitOrderActivity.finish();
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("支付结果");
            builder.setMessage(resp.errCode);
            builder.show();
        }
    }
}
